from jira import JIRA
from jira.client import JIRA
import re
from time import time
from datetime import datetime
from datetime import timedelta
import types

class JiraData(object):

    jira = ""
    def setJiraConnection(self):
        self.jira = JIRA("http://newjira.yanxiu.com",basic_auth=("autotester","autotester"))
        self.jira.kill_session()

    def closeJiraConnection(self):
        self.jira.kill_session()

    def getInfoByUser(self, user, timerange):
        startDate = timerange[0]
        endDate = timerange[1]
        if startDate.startswith("20"):
            startDate = "\"" + startDate + "\""
        if endDate.startswith("20"):
            endDate =  "\"" + endDate + "\""
        jql = "project = TMM AND assignee = " + user + " and duedate >= " + startDate + "AND duedate <= " + endDate
        self.setJiraConnection()
        results = self.jira.search_issues(jql,0,400)
        self.closeJiraConnection()
        return results

    def getAllTPR(self):
        jql = "project = TPR and type = '项目'"
        self.setJiraConnection()
        projects = self.jira.search_issues(jql,0,400)
        self.closeJiraConnection()
        return projects

    def getAllStory(self):
        jql = "project = TMM and type = 'Story'"
        self.setJiraConnection()
        stories = self.jira.search_issues(jql,0,400)
        self.closeJiraConnection()
        return stories

    def getIssueByKey(self,key):
        self.setJiraConnection()
        try:
            issue = self.jira.issue(key)
        except:
            return "Issue does not exits"
        else:
            return issue

    def setStartDate(self):
        jql = "project = TMM AND status != closed"
        self.setJiraConnection()
        tasks = self.jira.search_issues(jql,maxResults=400)
        for issue in tasks:
            key = issue.key
            type = issue.fields.issuetype
            osummary = issue.fields.summary
            oduedate = issue.fields.duedate
            ostorypoint = issue.fields.customfield_10002
            ostartdate = issue.fields.customfield_10200
            ocreatedDate = issue.fields.created[0:10]
            if (str(ostartdate).startswith("20") is not True) or (str(oduedate).startswith("20") is not True):
                """startdate或duedate为空时，为所有story和task填充 startdate & duedate 信息"""
                if str(oduedate).startswith("20"):
                    """如果duedate不为空，则startdate一定为空，用duedate - storypoint 得到 startdate"""
                    if isinstance(ostorypoint, float):
                            ustartdate = datetime.strptime(oduedate, "%Y-%m-%d")
                            for i in range (1, round(ostorypoint)):
                                ustartdate = ustartdate - timedelta(1)
                                if ustartdate.weekday() is 6:
                                    ustartdate = ustartdate - timedelta(2)
                    else:
                        """story points 为空时，默认为当天就能完成的事物，duedate 设为 startdate"""
                        ustartdate = oduedate
                    if isinstance(ustartdate, str) is not True:
                        ustartdate = datetime.strftime(ustartdate, "%Y-%m-%d")
                    issue.update(customfield_10200=ustartdate)
                    print(key, osummary, "startdate 已更新")
                else:
                    """duedate为空，如果startdate也为空，则先填充startdate信息，同时处理duedate"""
                    if str(ostartdate).startswith("20") is not True:
                        """并且startdate也为空，则用createdate填充startdate，并更新startdate"""
                        ustartdate = ocreatedDate
                        if isinstance(ustartdate, str) is not True:
                            ustartdate = datetime.strftime(ustartdate, "%Y-%m-%d")
                        issue.update(customfield_10200=ustartdate)
                        print(key, osummary, "startdate 已更新")
                    if isinstance(ostorypoint, float):
                        uduedate = datetime.strptime(ocreatedDate, "%Y-%m-%d")
                        for i in range (1, round(ostorypoint)):
                            uduedate = uduedate + timedelta(1)
                            if uduedate.weekday() is 5:
                                uduedate = uduedate + timedelta(2)
                    else:
                        """如果story points 和 duedate 都为空，则默认为当天完成事件，用createdate 填充 startdate 和 duedate"""
                        uduedate = ocreatedDate
                    if isinstance(uduedate, str) is not True:
                        uduedate = datetime.strftime(uduedate, "%Y-%m-%d")
                    issue.update(duedate = uduedate)
                    print (key, osummary, "duedate 已更新")
            else:
                pass
        self.closeJiraConnection()
